//
//  BTSchoolOfBusinessVC.m
//  BaxTer
//
//  Created by 陈武琦 on 16/8/30.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "BTSchoolOfBusinessVC.h"
#import "BTLoginVC.h"
#import "BTNavigationContrller.h"
#import "WSJPopview.h"
#import "XLPlainFlowLayout.h"
#import "BesinessSchoolItem.h"
#import "SchoolManagerSectionHeader.h"
#import "MJRefresh.h"
#import "CWQ_courseIntroductionCell.h"
#import "KCBannerView.h"
#import "BTSearchBar.h"
#import "HomepartBtn.h"
#import "UIView+YTXAnimateCSS.h"
#import "BTCourseDetailVC.h"
#import "BTMarketVC.h"
#import "BTTopicListVC.h"
#import "CWQ_historySearchVC.h"
#import "CWQ_SearchVC.h"
#import "BTNavigationContrller.h"
#import "BTSaleCategoryVC.h"
#import "BTBannerModel.h"
#import "BTHotListModel.h"
#import "BTTopicListVC.h"
#import "BTTrainingCampTool.h"
#import "BTTrainingVC.h"
#import "CWQ_MessageVC.h"
#import "BTTrainingCampVC.h"
#import "BTTopicDetailVC.h"
#import "CWQ_MessageVC.h"
#import "UIView+WZLBadge.h"
#import "BTBaseWebVC.h"
#import "NSString+Utilities.h"
#import "KLCPopup.h"

#define banerHight 180
@interface BTSchoolOfBusinessVC ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,KCBannerViewDataSource,KCBannerViewDelegate>



@property (nonatomic,  strong) KCBannerView *banner;

@property (nonatomic,  strong) BTSearchBar *searchBar;


@property (nonatomic,  strong) UIScrollView *partView;

@property (nonatomic,  strong) NSArray<BTBannerModel *> *bannerArr;

@property (nonatomic,  strong) NSMutableArray <BTHotListModel *>*hotCourseArr;

@property (nonatomic,  assign) NSInteger page;

@property (nonatomic,  strong) UIButton  *notiBtn;


@end

@implementation BTSchoolOfBusinessVC

- (instancetype)init {

    if (self = [super init]) {
        self.page = 1;
    }
    return self;

}
- (NSMutableArray *)hotCourseArr{
    if (!_hotCourseArr) {
        _hotCourseArr = [NSMutableArray array];
        
    }
    return _hotCourseArr;
}
#pragma mark -轮播视图
- (KCBannerView *)banner{
    if (!_banner) {
        // 创建
        _banner  = [[KCBannerView alloc] init];
    
        _banner.placeholderImageView.image = [UIImage imageNamed:@"暂无图片"];
        // 设置代理
        _banner.delegate = self;
        // 数据源
        _banner.dataSource = self;
        // 添加
    

    }
    return _banner;
}
#pragma mark -KCBannerViewDatasource
- (BTBannerModel *)bannerView:(KCBannerView *)bannerView bannerForItemAtIndex:(NSInteger)index
{
    return self.bannerArr[index];
}

- (NSInteger)numberOfBannersInBannerView:(KCBannerView *)bannerView
{
    return self.bannerArr.count;
}
#pragma mark -轮播被点击
- (void)bannerView:(KCBannerView *)bannerView didSelectBannerAtIndex:(NSInteger)index{
    BTBannerModel *bannerModel = self.bannerArr[index];
    [self gotoToRelativeCourseWith:[bannerModel.generalizeType integerValue] with:[bannerModel.generalizeContent integerValue] with:bannerModel.name ifIsConsultWithType:bannerModel.infoType andQuestionId:[bannerModel.infoQuestionID integerValue]];
    
    NSLog(@"%@",bannerModel);
}


- (UIScrollView *)partView{
 
    if (!_partView) {
       
        NSArray *imageArr = @[@"训练营",@"市场",@"销售",@"专题"];
        NSArray *titleArr = @[@"训练营",@"市场",@"销售",@"专题"];
        _partView = [[UIScrollView alloc] init];
        
        CGFloat f = kScreenFactor;
        CGFloat w = kScreenWidth /4;
        CGFloat h = 100 * f;
         _partView.frame = CGRectMake(0, banerHight * f, kScreenWidth, h);
        for (int i = 0; i < 4 ;i++ ) {
            HomepartBtn *btn =[HomepartBtn buttonWithType:UIButtonTypeCustom];
            [btn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
            [btn setTitle:titleArr[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            btn.titleLabel.textAlignment = NSTextAlignmentCenter;
            btn.frame = CGRectMake(i * w, 0, w, h);
            btn.titleLabel.font = [UIFont systemFontOfSize:14];
            btn.tag = 900 +i;
            btn.backgroundColor = [UIColor whiteColor];
            [btn addTarget:self action:@selector(partViewClicked:) forControlEvents:UIControlEventTouchUpInside];
            [_partView addSubview:btn];
        }
        _partView.pagingEnabled = YES;
        if (titleArr.count > 4) {
            _partView.contentSize = CGSizeMake(kScreenWidth *2, h);
        }
        _partView.showsHorizontalScrollIndicator = NO;
        
    }
    return _partView;
}
#pragma mark -partView 被点击
- (void)partViewClicked:(UIButton *)btn{
    NSInteger tag =  btn.tag - 900;
    switch (tag) {
        case 0:{
           
            NSNumber *campId = [BTTrainingCampTool getLastTrainingCampIdForUser];

            if (!campId) {
                [self getThelastTrainingCamp];
            }else{
                BTTrainingCampVC *vc =[BTTrainingCampVC new];
                vc.trainingId = [campId integerValue];
                [self.navigationController setNavigationBarHidden:YES animated:YES];
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        
        }
          
        case 1:
            
            [self.navigationController pushViewController:[BTMarketVC new] animated:YES];
            
            break;
        case 2:
            
             [self.navigationController pushViewController:[BTSaleCategoryVC new] animated:YES];
            
            break;
        case 3:
            
            //专题
            [self.navigationController pushViewController:[BTTopicListVC new] animated:YES];
            
            break;
        
            
        default:
            break;
    }

}




- (BTSearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar = [BTSearchBar searchBarWithDelegate:self];
        
    }
    return _searchBar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshDataSource) name:LoginSuccessNotification object:nil];
    if (!BT_USERID) {
     
        BTLoginVC *loginVC = [BTLoginVC new];
        BTNavigationContrller *nav = [[BTNavigationContrller alloc] initWithRootViewController:loginVC];
        [self presentViewController:nav animated:NO completion:nil];

        
    }else{
        
        [self getHotCourseList:YES];
        [self getBanerData];
        [self requestNoticeData];
        [self getMyLoginReward];
    }
   
   
}
- (void)configUI{

    
  
    
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight- 64- 49);
    [self.view addSubview:self.tableView];
    
    self.navigationItem.titleView = self.searchBar;
 
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"铃铛"] forState:UIControlStateNormal];

    [btn addTarget:self action:@selector(noticePress) forControlEvents:UIControlEventTouchUpInside];
    [btn showBadgeWithStyle:WBadgeStyleRedDot value:1 animationType:WBadgeAnimTypeBreathe];
     btn.badgeCenterOffset = CGPointMake(22, 8);
    btn.frame = CGRectMake(0, 0, 33, 33);
    self.notiBtn = btn;
   
    
    UIBarButtonItem *spaceFix = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    spaceFix.width = 14;
    UIBarButtonItem *rightItem =[[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItems = @[rightItem,spaceFix];
    [self.tableView registerNib:[UINib nibWithNibName:@"CWQ_courseIntroductionCell" bundle:nil] forCellReuseIdentifier:@"CWQ_courseIntroductionCell"];
    weakSelf_define;
    [self.tableView wsj_HeaderRefreshBlock:^{
        [weakSelf getHotCourseList:YES];
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf getHotCourseList:NO];
    }];
    
    
    
    self.tableView.backgroundColor = kAppBg;
    UIView *view=[UIView new];
    
    CGFloat f = kScreenFactor;
    [view addSubview:self.partView];
    [view addSubview:self.banner];
    self.banner.frame = CGRectMake(0, 0, kScreenWidth, f * banerHight);
    self.banner.backgroundColor = [UIColor redColor];
    view.backgroundColor = [UIColor whiteColor];
    UIView *line =[UIView new];
    line.backgroundColor = HexRGB_WSJ(231, 231, 231);
    line.frame =CGRectMake(0, (banerHight + 100 )*f, kScreenWidth, 4);
    [view addSubview:line];
    view.frame = CGRectMake(0, 0, kScreenWidth, (banerHight + 100 )*f+4);
    //    view.backgroundColor  =[UIColor purpleColor];
    self.tableView.tableHeaderView = view;

    
    
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
  

}
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    if (BT_USERID) {
        [self requestNoticeData];
    }
   


    
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}


#pragma -mark 请求baner数据

- (void)getBanerData{
    weakSelf_define;
    [[BTNetworkManager sharedMg] POST:kGetBanner parameters:@{@"bannerType":@(1)} success:^(NSDictionary *responseObject) {
         if (responseObject[@"data"]) {
             NSArray<NSDictionary *> *arr = responseObject[@"data"] ;
             if ([arr isKindOfClass:[NSArray class]])  {
                 weakSelf.bannerArr = [BTBannerModel mj_objectArrayWithKeyValuesArray:arr];
              
             }
             NSMutableArray *bannerImageArr =[NSMutableArray array];
             [weakSelf.bannerArr enumerateObjectsUsingBlock:^(BTBannerModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                 if (obj.bannerImage) {
                      [bannerImageArr addObject:[NSURL URLWithString:obj.bannerImage]];
                 }
                
             }];
             [weakSelf.banner reloadData];
         }
         if (responseObject_Err) {
             alertMessage(responseObject[@"err"]);
         }
         
     } failure:^(NSString *err) {
         alertMessage(err);
     }];
    
}


#pragma -mark 请求热门推荐

- (void)getHotCourseList:(BOOL)isRecover{

    if (!BT_USERID) {
//        return;
    }
    if (isRecover) {
         self.page = 1;
    }else{
        self.page ++;

    }
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    
    params[@"page"] = @(self.page);
    params[@"rows"] = @(10);
    //wsjtest
//    params[@"userId"]= @(1);
   
    weakSelf_define;

    self.tableView.loading=  YES;
    [[BTNetworkManager sharedMg] POST:kGetHotCourseList parameters:params success:^(NSDictionary *responseObject) {
        weakSelf.tableView.loading=  NO;
        [weakSelf.tableView.footer endRefreshing];
        [weakSelf.tableView.header endRefreshing];
        if (responseObject_success) {
            NSDictionary *dic = responseObject[@"data"];
            if ([dic[@"data"] isKindOfClass:[NSArray class]]) {
                //总页数
                NSInteger totalPage;
                
                if ([dic[@"totalPage"] isKindOfClass:[NSNull class]] ) {
                    totalPage = 0;
                }else{
                    totalPage = [dic[@"totalPage"] integerValue];;
                }
                
//                总条数
                NSInteger currentPage = [dic[@"page"] integerValue];
                
                
                if (currentPage >=totalPage) {
                    [weakSelf.tableView.footer noticeNoMoreData];
                    
                }else{
                    [weakSelf.tableView.footer resetNoMoreData];
                  
                }
                if (isRecover) {
                    [weakSelf.hotCourseArr removeAllObjects];
                   
                }
                [weakSelf.hotCourseArr addObjectsFromArray:[BTHotListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]]];
              
              
            }
            
        }
        if (weakSelf.hotCourseArr.count == 0) {
            weakSelf.tableView.footer.hidden = YES;
        }else{
           weakSelf.tableView.footer.hidden = NO;
        }
 
        [weakSelf.tableView reloadData];
        
        
    } failure:^(NSString *err) {
        weakSelf.tableView.loading=  NO;
        [weakSelf.tableView.footer endRefreshing];
        [weakSelf.tableView.header endRefreshing];
    }];

    

}


#pragma -mark 获取登陆积分
- (void)getMyLoginReward{
    
    [[BTNetworkManager sharedMg] POST:kGetMyLoginReward parameters:nil success:^(id responseObject) {
        if (responseObject_success) {
            NSString *infor = responseObject[@"data"];
            if ([infor isKindOfClass:[NSString class]]) {
                [[WSJPopview sharedWsjPopView] showLoginWelcome];;
            }
        }
    } failure:^(NSString *err) {
        
    }];
    
}


#pragma -mark  第一次获取训练营
- (void)getThelastTrainingCamp{
    
     cwqHud;
    weakSelf_define;
     [[BTNetworkManager sharedMg] POST:kGetLastTrainingCamp parameters:nil success:^(NSDictionary * responseObject) {
           [hud hide:YES];
         if (responseObject_success) {
             if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                 NSInteger campId = [responseObject[@"data"][@"campId"] integerValue];
                 BTTrainingCampVC *vc =[BTTrainingCampVC new];
                 [weakSelf.navigationController setNavigationBarHidden:YES animated:YES];
                 vc.trainingId = campId;
                 [weakSelf.navigationController pushViewController:vc animated:YES];
             }else{
                 alertMessage(@"没有相关训练营~");
             }
            
         }
     } failure:^(NSString *err) {
         
     }];
}

#pragma -mark- --------------------获取通知消息----------------------
- (void)requestNoticeData {
    

    weakSelf_define;
    [[BTNetworkManager sharedMg] POST:BTNotifyReadUrl parameters:nil success:^(id responseObject) {
        if (responseObject_success) {
           
            if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
               
                if([responseObject[@"data"][@"notReadNum"] integerValue]>0){

                    [weakSelf.notiBtn resumeBadge];
                } else {
                
                    [weakSelf.notiBtn clearBadge];
                }
             
                
            }else{
                [weakSelf.notiBtn clearBadge];
            }
         
        }
    } failure:^(NSString *err) {
        
    }];
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
   
    
    CWQ_historySearchVC *historySearchVC = [CWQ_historySearchVC new];
    historySearchVC.searchType = CWQ_historySearchVCType_Course_ShangXueyuan;
    [self.navigationController pushViewController:historySearchVC animated:YES];
    return NO;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.hotCourseArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 30;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   
    UIView *view =[[UIView alloc] init];
    view.frame = CGRectMake(0, 0, kScreenWidth, 30);
    view.backgroundColor = [UIColor whiteColor];
    
    UIImageView *imageView =[[UIImageView alloc] init];
    imageView.frame = CGRectMake(10, 10, 2, 14);
    imageView.image = [UIImage imageNamed:@"horizenLine"];
    [view addSubview:imageView];
    
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(20, 7, 200, 20);
    label.font =[UIFont systemFontOfSize:14];
    label.text = @"热门推荐";
    [view addSubview:label];
    
    
    return view;
  
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CWQ_courseIntroductionCell *cell  =[tableView dequeueReusableCellWithIdentifier:@"CWQ_courseIntroductionCell" forIndexPath:indexPath];
    BTHotListModel *model = self.hotCourseArr[indexPath.row];
    cell.hotModel = model;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

   
    return 110;
}


#pragma mark -请求数据
- (void)refreshDataSource {

    //重新初始化数据库/切换
    [[RLMCourseManager manager] configWithUserAccout:BT_USERID];
    [self getBanerData];
    [self getHotCourseList:YES];
    
    [self getMyLoginReward];
  

}
#pragma mark -进入通知
- (void)noticePress {
    CWQ_MessageVC *messageVC = [CWQ_MessageVC new];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController pushViewController:messageVC animated:YES];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

//BTCourseListModel.h
    BTHotListModel *model = self.hotCourseArr[indexPath.row];
   
    [self gotoToRelativeCourseWith:[model.generalizeType integerValue] with:[model.generalizeContent integerValue] with:model.contentName ifIsConsultWithType:model.infoType andQuestionId:[model.infoQuestionID integerValue]];
    
}


- (void)gotoToRelativeCourseWith:(NSInteger)generalizeContent with:(NSInteger)modelId with:(NSString *)name ifIsConsultWithType:(NSString *)infoType andQuestionId:(NSInteger)infoQuestionID{
    NSInteger type = generalizeContent;
    NSInteger itemId = modelId;
    if (type ==1) {
        BTCourseDetailVC *vc =[BTCourseDetailVC new];
        vc.courseId = itemId;
        [self.navigationController pushViewController:vc animated:YES];
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        return;
    }
    if (type ==2) {
        BTTopicDetailVC *vc =[BTTopicDetailVC new];
        vc.topicId = itemId;
        vc.title = name;
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    if (type==3) {
        
       
        BTBaseWebVC *vc =[BTBaseWebVC new];
        NSString *typeStr = nil;
        NSString *url;
        if ([infoType isEqualToString:@"ORDINARY"]) {
            typeStr = kConsultDetail;
            url = [NSString stringWithFormat:@"%@/%@/%@",[BTNetworkManager sharedMg].bathURL,typeStr,@(modelId)];
        }else if([infoType isEqualToString:@"QUESTION"]){
            typeStr = kQuestionDetai;
            url = [NSString stringWithFormat:@"%@/%@/%@",[BTNetworkManager sharedMg].bathURL,typeStr,@(infoQuestionID)];
        }
     
        vc.tagKey  =  @"consult";
        vc.url =url;
    
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
   

}



@end
